<?php
namespace App\Libs\wrapper;

use App\Models\Menus;
use Illuminate\Support\Facades\DB;

class Menu extends Comm{
//////////////////////////////////////////////// 菜单
////////////////////// 菜单列表

    protected $menuModel;

    public function __construct()
    {
        $this->menuModel = new Menus();
    }

    /**
	 * 菜单列表
	 * @param name 菜单名称
	 * @param fid 父id
	 */
	public function menu_list($data){
		$where = "1=1";
		//name 菜单名称
		if(!empty($data['name'])){
			$where .= " and `name` like '%{$data['name']}%'";
		}
		//fid 父id
		if(isset($data['fid'])){
			$where .= " and fid='{$data['fid']}'";
		}
		
		$sql = "select *
					from xt_menus
					where {$where}
					order by serial_number asc";
		$list = json_decode(json_encode(db::select($sql)),true);
		return $list;
	}

    /**
     * @Desc:菜单列表
     * @param $data
     * @return mixed
     * @author: Liu Sinian
     * @Time: 2023/2/21 17:59
     */
    public function getMenuList($data)
    {
//        DB::connection()->enableQueryLog(); // 开启监听sql
        // 菜单列表过滤器
        $result = $this->_filterMenuList($data);

//        var_dump(DB::getQueryLog());exit(); // 打印sql
        // 格式化菜单列表
        $this->_formatMenuList($result['list'], $data['level']);

        return $result;
    }

    /**
     * @Desc:菜单列表查询过滤器
     * @param $data
     * @return array
     * @author: Liu Sinian
     * @Time: 2023/2/21 17:59
     */
    private function _filterMenuList($data)
    {
//        $list = $this->menuModel::query();
        $list = DB::table('xt_menus');
        // 过滤名称
        if (isset($data['name']) && !empty($data['name']))
        {
            $list->where('name', 'like', '%'.$data['name'].'%');
        }
        // 过滤上级id
        if (isset($data['fid']))
        {
            $list->whereIn('fid', (array)$data['fid']);
//            $list->whereIn('fid', [0]);
        }

        // 过滤标识
        if (isset($data['identity']) && !empty($data['identity']))
        {
            $list->where('identity', 'like', '%'.$data['identity'].'%');
        }
        // 过滤菜单id
        if (isset($data['Id']) && !empty($data['Id']))
        {
            $list->whereIn('Id', (array)$data['Id']);
        }

        $count = $list->count();

        if (isset($data['limit']) || isset($data['page'])){
            $page = $data['page'] ?? 1;
            $limit = $data['limit'] ?? 30;
            $pagenum = $page <= 1 ? 0 : ($page-1)*$limit;
            $list = $list->offset($pagenum)
                ->limit($limit);
        }
        $list = $list->orderBy('serial_number', 'asc')
            ->get();

		$list = json_decode(json_encode($list),true);
;

        return ['count' => $count, 'list' => $list];
    }

    /**
     * @Desc: 判断菜单是否有下级菜单
     * @param $list
     * @return mixed
     * @author: Liu Sinian
     * @Time: 2023/2/27 9:54
     */
    public function _formatMenuList(&$list, $level)
    {
        /**
         * level 规则：
         *  0 --不设置level参数，直接返回查询数据
         *  1 --对应菜单一级权限
         *  2 --对应菜单二级权限
         *  3 --对应菜单三级权限
         */
        if (!empty($level)){
            foreach ($list as &$item){
                $item['level'] = $level;
                $menu =  DB::table('xt_menus')->where('fid', $item['Id'])->first();
                if (!empty($menu)){
                    $item['child'] = true;
                }else{
                    $item['child'] = false;
                }
            }
        }

        return $list;
    }
	
	/**
	 * 新增菜单
	 * @param name 名称
	 * @param url 路径
	 * @param icon 图标
	 * @param fid 父id
	 * @param serial_number 序号
	 * @param identity 权限标识
	 */
	public function menu_add($data){
		$field = "";
		$insert = "";
		//name 菜单名称
		if(!empty($data['name'])){
			$field .= ",`name`";
			$insert .= ",'{$data['name']}'";
		}
		//url 路径
		if(!empty($data['url'])){
			$field .= ",`url`";
			$insert .= ",'{$data['url']}'";
		}
		//icon 图标
		if(!empty($data['icon'])){
			$field .= ",`icon`";
			$insert .= ",'{$data['icon']}'";
		}
		//fid 父id
		if(!empty($data['fid'])){
			$field .= ",`fid`";
			$insert .= ",{$data['fid']}";
		}
		//serial_number 序号
		if(!empty($data['serial_number'])){
			$field .= ",`serial_number`";
			$insert .= ",{$data['serial_number']}";
		}
		//identity 权限标识
		if(!empty($data['identity'])){
			$sql = "select `Id`
						from xt_powers
						where `identity`='{$data['identity']}'";
			$power_find = db::select($sql);
			if(empty($power_find)){
				return '该标识必须与权限标识一致，无该标识';
			}
			
			$field .= ",`identity`";
			$insert .= ",'{$data['identity']}'";
		}
		
		if(empty($field) || empty($insert)){
			return '新增数据为空';
		}
		$field = substr($field, 1);
		$insert = substr($insert, 1);
		$sql = "insert into xt_menus({$field}) values ({$insert})";
		$add = db::insert($sql);
		if($add){
			return 1;
		}else{
			return '新增失败';
		}
	}
	
	/**
	 * 菜单信息
	 * @param menu_id 菜单id
	 */
	public function menu_info($data){
		$where = "1=1";
		//menu_id 菜单id
		if(!empty($data['menu_id'])){
			$where .= " and `Id`={$data['menu_id']}";
		}
		
		//权限信息
		$sql = "select * from `menus` where {$where}";
		$find = json_decode(json_encode(db::select($sql)),true);
		if(is_array($find)){
			return $find;
		}else{
			return '获取失败';
		}
	}
	
	/**
	 * 编辑菜单
	 * @apram Id 菜单id
	 * @param name 菜单名称
	 * @param url 路径
	 * @param icon 图标
	 * @param fid 父id
	 * @param serial_number 序号
	 * @param identity 权限标识
	 */
	public function menu_update($data){
		$set = "";
		
		//name 菜单名称
		if(!empty($data['name'])){
			$set .= ",`name`='{$data['name']}'";
		}
		//url 路径
		$set .= ",`url`='{$data['url']}'";
		//icon 图标
		if(!empty($data['icon'])){
			$set .= ",`icon`='{$data['icon']}'";
		}
		//fid 父id
		if(!empty($data['fid'])){
			$set .= ",`fid`={$data['fid']}";
		}
		//serial_number 序号
		if(!empty($data['serial_number'])){
			$set .= ",`serial_number`={$data['serial_number']}";
		}
		//identity 权限标识
		$set .= ",`identity`='{$data['identity']}'";
		if(!empty($data['identity'])){
			$sql = "select `Id`
						from xt_powers
						where `identity`='{$data['identity']}'";
			$power_find = db::select($sql);
			if(empty($power_find)){
				return '该标识必须与权限标识一致，无该标识';
			}
		}
		
		if(empty($set)){
			return '无修改数据';
		}
		
		$set = substr($set, 1);
		$sql = "update xt_menus
					set {$set}
					where `Id` = {$data['Id']}";
		$update = db::update($sql);
		if($update !== false){
			return 1;
		}else{
			return '编辑失败';
		}
	}
	
	/**
	 * 删除菜单
	 * @param Id 菜单id
	 */
	public function menu_del($data){
		$where = "1=1";
		//Id 菜单id
		if(!empty($data['Id'])){
			$where .= " and (`Id`={$data['Id']} or `fid`={$data['Id']})";
		}
		
		if($where == '1=1'){
			return '删除条件为空';
		}
		
		$sql = "delete
					from xt_menus
					where {$where}";
		$del = db::delete($sql);
		if($del){
			return 1;
		}else{
			return '删除失败';
		}
	}


    /**
     * 新增菜单说明文档
     */
    public function menu_doc_add($data){
        $doc = DB::table('xt_menus_doc')->where('menus_id',$data['menus_id'])->select('id')->first();
        $date = date('Y-m-d H:i:s');
        if(!empty($doc)){
            DB::table('xt_menus_doc')->where('id',$doc->id)->update([
                'content'=>$data['content'],
                'title'=>$data['title'],
                'updatetime'=>$date
            ]);
            return 1;
        }else{
            $insert = DB::table('xt_menus_doc')->insert([
                'menus_id'=>$data['menus_id'],
                'content'=>$data['content'],
                'title'=>$data['title'],
                'addtime'=>$date,
                'updatetime'=>$date
            ]);
            if($insert){
                return 1;
            }
        }
    }

    /**
     * 新增菜单说明文档
     */
    public function menu_doc_update($data){
        $doc = DB::table('xt_menus_doc')->where('menus_id',$data['menus_id'])->select('id')->first();
        $date = date('Y-m-d H:i:s');
        if(!empty($doc)){
            DB::table('xt_menus_doc')->where('id',$doc->id)->update([
                'content'=>$data['content'],
                'title'=>$data['title'],
                'updatetime'=>$date
            ]);
            return 1;
        }else{
            return false;
        }
    }



    /**
     * 查看菜单说明文档
     */
    public function menu_doc_select($data){

        $doc = DB::table('xt_menus_doc')->where('menus_id',$data['menus_id'])->first();

        return $doc;
    }

    /**
     * 查看说明文档菜单
     */
    public function menus_select($data){

        $doc_list = DB::table('xt_menus_doc')->where('menus_id',$data['menus_id'])->select('id','name')->get()->toArray();

        return $doc_list;
    }
		
		
		
	
	
















}//结束符